import {ipcMain} from 'electron'
import kafkaService from './kafkaService'

let initMessage = mainWindow => {
  // 主进程接收渲染进程的消息,并返回一个结果
  ipcMain.handle('sendMessageChannel', async function (event, topic, message) {
    try {
      let result = await kafkaService.sendMessage(topic, message)
      // 如果发送成功
      if (result && result[0]) {
        if (result[0].errorCode === 0) {
          //console.log('发送主进程消息')
          mainWindow.webContents.send('successChannel', 1)
        }
      }
    } catch (e) {
      console.log(e)
      mainWindow.webContents.send('failChannel', 1)
    }
  })

  /**
   * 连接kafka的channel,点击'连接'按钮触发
   */
  ipcMain.handle('connectKafkaChannel', async function (event, brokers) {
    try {
      console.log('开始连接kafka:', brokers)
      await kafkaService.initKafka('protocol42-generator', brokers)
      // 向界面发送'连接成功'消息
      mainWindow.webContents.send('connectKafkaSuccessChannel', 1)
    } catch (e) {
      console.log(e)
    }
  })

  /**
   * 开启DevTools的channel
   */
  ipcMain.handle('open-devtools', async function (event, brokers) {
    mainWindow.webContents.openDevTools()
  })
}

export default {initMessage}
